package com.cjkj.equipment.job;

import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.equipment.domain.MonitorPadData;
import com.cjkj.equipment.domain.dto.BreathAndHeartAVGDto;
import com.cjkj.equipment.mapper.MonitorPadDataMapper;
import com.cjkj.equipment.service.MonitorPadDataService;
import com.cjkj.equipment.utils.SleepStageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@EnableScheduling
@Component
@Slf4j
public class SleepJob {

    @Resource
    MonitorPadDataMapper monitorPadDataMapper;

    @Resource
    private MonitorPadDataService monitorPadDataService;

    /**
     * 每天八点执行，每10分钟一次
     */
    @Scheduled(cron = "0 0/10 8 * * ? ")
    public void job() {
        log.info("*****************************睡眠报告任务启动*************************");
        // 当前时间
        Date now = new Date();
        // 当天的18点
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date time18 = calendar.getTime();
        // 如果当前时间还没到18:00，则将查询日期改为昨天的18点
        if (now.before(time18)) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            time18 = calendar.getTime();
        }

        calendar.add(Calendar.DAY_OF_MONTH,1);
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        Date reportEndTime = calendar.getTime();

        // 查询18点有数据上传的设备
        List<MonitorPadData> equipmentList = monitorPadDataMapper.getEquipmentNo(time18);
        /*
         * 遍历所有设备，取出前第25条在床数据作为基准数据
         * 然后以这25条数据最后一条数据的时间为start，最后一条数据采集时间为end查询出设备no和设备时间和平均心率，进行判断睡眠状态
         */
        for (MonitorPadData monitorPadData : equipmentList) {
            String equipmentNo = monitorPadData.getEquipmentNo();
            List<MonitorPadData> benchmarkData = monitorPadDataMapper.getEquipmentNodata25(equipmentNo, time18);
            // 基准数据是否不为空且长度为25
            boolean dataIsEmpty = StringUtils.isNotNull(benchmarkData) && benchmarkData.size() == 25;
            if (dataIsEmpty) {
                BreathAndHeartAVGDto avgDto = SleepStageUtil.calculateAVG(benchmarkData);
                monitorPadDataService.inertSleepStageData(equipmentNo, benchmarkData, avgDto, reportEndTime);
            }
        }
        log.info("*****************************睡眠报告任务完成*************************");

    }
}
